package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.UserMapper;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.PasswordUtils;
import com.zzyl.vo.LoginVo;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description LoginServiceImpl
 * @Author Lisheng Li
 * @Date 2025-09-01
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserVo login(LoginDto loginDto) {

        //根据用户名查数据
        User user = userMapper.check(loginDto.getUsername());
        //验证密码是否正确
        if (!PasswordUtils.verifyPassword(loginDto.getPassword(),user.getPassword())){
            throw  new BaseException(BasicEnum.ORIGINAL_PASSWORD_ERROR);
        }

        if (user!=null){

            Map<String, Object> map = new HashMap<>();
            map.put("nickName", user.getNickName());

//            //read 很关键，获取用户id
//            map.put("id",user.getCreateBy());
//            //read 👆
            String userToken= JwtUtil.createJWT("gzhm666",600000,map);

            UserVo userVo = BeanUtil.toBean(user, UserVo.class);
            userVo.setUserToken(userToken);
            return userVo;
        }
        return null;
    }
}
